package Java9_23;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

public class Products4 {
    public static double goumai(int it, int st) {
        double money=0;
        SAXReader reader = new SAXReader();
        try {
            Document doc=reader.read(new File("D:\\IdeaProjects\\src\\Java9_23\\products.xml"));
            List<Element>list=doc.selectNodes("/shop/product[itemno="+it+"]");
            if (list.size()!=0){
                Element e=list.get(0);
                boolean discount=Boolean.parseBoolean(e.attributeValue("discount"));
                Element eprice= (Element) e.selectSingleNode("price");
                double price=Double.parseDouble(eprice.getTextTrim());
                Element estockcount= (Element) e.selectSingleNode("stockcount");
                int stockcount = Integer.parseInt(estockcount.getTextTrim());
                if (st>stockcount){
                    System.out.println("购买的数量大于现有的存货");
                }else if (discount==true){
                    money=price*st*0.7;
                    System.out.println("购买了折扣后付费"+money);
                }else if (discount=false){
                    money=price*st;
                    System.out.println("购买了不打折商品后付费"+money);
                }
                estockcount.setText(String.valueOf(stockcount-st));
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("UTF-8");
                XMLWriter xw=new XMLWriter(new FileOutputStream("D:\\IdeaProjects\\src\\Java9_23\\products.xml"),format);
                xw.write(doc);
                xw.close();
                System.out.println("成功打印");
            }else if (list.size()==0){
                System.out.println("没有此商品");
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return money;
    }

    public static void main(String[] args) {
        goumai(2951,10);
    }
}
